package com.ant.http

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.util.concurrent.TimeUnit

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:一个 httpClient对应 一个Retrofit，但是OkHttpClient只需要一个
 */

class HttpClient(baseUrl: String) {

    companion object {
        private val TAG: String = HttpClient::class.java.simpleName

        //存储 一个retrofit可能会存在很多个 Service
        private val serviceMap = HashMap<Int, HttpService>()

        val okHttpClient: OkHttpClient by lazy {


            "okHttpClient 初始化".println()

            val builder =
                OkHttpClient.Builder()
                    .readTimeout(HttpConfig.HTTP_TIME_OUT_READE, TimeUnit.SECONDS)
                    .writeTimeout(HttpConfig.HTTP_TIME_OUT_WRITE, TimeUnit.SECONDS)
                    .connectTimeout(HttpConfig.HTTP_TIME_OUT_CONNECTION, TimeUnit.SECONDS)
//                    .retryOnConnectionFailure()
            //添加拦截器
            HttpConfig.mInterceptors.forEach {
                builder.addInterceptor(it)
            }
            //是否开启代理模式
            if (!HttpConfig.isDebug && !HttpConfig.proxyEnable) {
                builder.proxy(Proxy.NO_PROXY)
            }
            builder.build()
        }
    }


    private val retrofit: Retrofit

    init {
        retrofit =
            Retrofit.Builder().baseUrl(baseUrl)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build()

    }


    /**
     * @return 指定service实例
     */
    fun <T : HttpService> getService(clazz: Class<T>): T {
        if (serviceMap.containsKey(clazz.hashCode())) {
            serviceMap[clazz.hashCode()]?.let {
                return it as T
            }
        }
        return initService(clazz)
    }


    private fun <T : HttpService> initService(clazz: Class<T>): T {
        val service: T = retrofit.create(clazz)
        serviceMap[clazz.hashCode()] = service
        return service
    }

}